package com.shoeshopping.dao;

import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;


@Repository("baseDao")
public class BaseDaoImpl implements BaseDao {
	
	@Resource
	HibernateTemplate hibernateTemplate;
	
	@Override
	public void save(Object entity) {
		hibernateTemplate.saveOrUpdate(entity);
	}

	@Override
	public void update(Object entity) {
		save(entity);
	}

	@Override
	public void delete(Object entity) {
		hibernateTemplate.delete(entity);
	}

	/**
	 * 分页，排序查询
	 * @param hql 查询的hql语句
	 * @param param 参数列表
	 * @param page 页数
	 * @param rows 查询的行数
	 * @param sort 排序字段名
	 * @param order 升降序
	 */
	@Override
	public List findWithPageAndSort(final String hql, final List<Object> param,
			final int page, final int rows, final String sort, final String order) {
		List list = null ;
		list = hibernateTemplate.executeFind(
				new HibernateCallback() {

					@Override
					public List doInHibernate(Session session)
							throws HibernateException, SQLException {
						
						String orderHql = hql;
						if(sort != null && order != null){
							orderHql = setSort(hql,sort, order);
						}
						
						Query query = session.createQuery(orderHql);
						if(param != null){
							setParam(query,param);
						}
						if(page != 0 && rows != 0){
							setPage(query,page, rows);
						}
						return query.list();
					}

				});
		return list;
	}
	
	private void setParam(Query query,List<Object> param) {
		for (int i = 0; i < param.size(); i++) {
			query.setParameter(i, param.get(i));
		}
	}
	
	private void setPage(Query query,int page, int rows){
		query.setFirstResult((page-1)*rows);
		query.setMaxResults(rows);
	}
	
	private String setSort(String hql,String sort, String order){
		hql += " order by "+sort+" "+order;
		System.out.println("setSort : "+hql);
		return hql;
	}

	@Override
	public List find(final String hql) {
		List list = null;
		list = hibernateTemplate.executeFind(new HibernateCallback() {

			@Override
			public List doInHibernate(Session session) throws HibernateException,
					SQLException {
				Query query = session.createQuery(hql);
				return query.list();
			}
		});
		return list;
	}

	@Override
	public List find(String hql, List<Object> param) {
		return findWithPageAndSort(hql, param, 0, 0, null, null);
	}

	@Override
	public List findWithPage(String hql, List<Object> param, int page, int rows) {
		return findWithPageAndSort(hql, param, page, rows, null, null);
	}

	@Override
	public List findWithSort(String hql, List<Object> param, String sort,
			String order) {
		return findWithPageAndSort(hql, param, 0, 0, sort, order);
		
	}

}
